package com.gopay.cashier.service.remote.impl;

import com.gopay.cashier.service.BankPayCallBackService;
import com.gopay.cashier.web.command.BankPayCallbackCommand;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.exception.GopayException;
import com.gopay.common.proccode.DicProcCodeService;
import com.gopay.common.util.DateUtils;
import com.gopay.common.util.RSAEncoderUtil;
import com.gopay.remote.cashier.bis.CashierBgNotifyRemoteService;
import com.gopay.remote.cashier.vo.CashierBgNotifyRespMsg;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;

/**
 * description ：bis  调用  cashier 后台通知实现类
 * edit by ：lx
 * datetime ：2017/9/30 11:13
 */
@Service("cashierBgNotifyRemoteService")
public class CashierBgNotifyRemoteServiceImpl implements CashierBgNotifyRemoteService {
    protected final static Log logger = LogFactory.getLog(CashierBgNotifyRemoteServiceImpl.class);

    @Resource(name = "bankPayCallBackService")
    private BankPayCallBackService bankPayCallBackService;
    @Autowired
    protected DicProcCodeService dicProcCodeService;

    @Override
    public CashierBgNotifyRespMsg callBgNotify(Map<String, String> param) {
        logger.debug(ToStringBuilder.reflectionToString(param));
        CashierBgNotifyRespMsg cashierBgNotifyRespMsg = new CashierBgNotifyRespMsg();
        BankPayCallbackCommand command = new BankPayCallbackCommand();
        command.setAmt(param.get("amt"));
        command.setCardType(param.get("cardType"));
        command.setNotifyNum(param.get("notifyNum"));
        command.setOrderId(param.get("orderId"));
        command.setPayStatus(param.get("payStatus"));
        command.setRetCode(param.get("retCode"));
        command.setRetMsg(param.get("retMsg"));
        command.setSign(param.get("sign"));

        System.out.println("cashier get signVal===:"+param.get("sign"));

        String plain = sign(command);
        logger.error("sign verify plain : "+ plain);
       /* try {
            if(!RSAEncoderUtil.verify(plain, command.getSign())){
                logger.error("sign is not fit, which orderId is "+ command.getOrderId());
                cashierBgNotifyRespMsg.setRespCode(ProcCodeConstants.PROC_CODE_100E8004);
                return cashierBgNotifyRespMsg;
            }else{
                logger.error("sign verify success, which orderId is "+ command.getOrderId());
            }
        } catch (Exception e1) {
            logger.error("verify sign error", e1);
            cashierBgNotifyRespMsg.setRespCode(ProcCodeConstants.PROC_CODE_200F1002);
            return cashierBgNotifyRespMsg;
        }*/ //由于 base 64 验签解码 中文乱码 导致验证不通过 所以注掉

        String resCode = null;
        try{
            logger.info("cashier callback receive:" + command.getOrderId()+" at "+ DateUtils.getCurrDate());
            boolean res = bankPayCallBackService.callBackProcess(command);
            resCode = res==true? ProcCodeConstants.PROC_CODE_100S1000:ProcCodeConstants.PROC_CODE_200F1002;
        }catch (GopayException e){
            logger.error(e.getMessage());
            resCode = e.getErrCode();
        }catch (Exception e){
            resCode=ProcCodeConstants.PROC_CODE_100F1002;
            logger.error(e);
        }
        cashierBgNotifyRespMsg.setRespCode(resCode);
        cashierBgNotifyRespMsg.setRespMsg(buildResponse(resCode,command.getOrderId()));
        return cashierBgNotifyRespMsg;
    }

    public String sign(BankPayCallbackCommand orderInfo) {
        StringBuffer sign = new StringBuffer();
        String orderId = orderInfo.getOrderId();
        String amt = orderInfo.getAmt();
        String retCode = orderInfo.getRetCode();
        String retMsg = orderInfo.getRetMsg();
        String payStatus = orderInfo.getPayStatus();
        String notifyNum = orderInfo.getNotifyNum();
        String cardType = orderInfo.getCardType();
        sign.append(orderId).append("|");
        sign.append(amt).append("|");
        sign.append(retCode).append("|");
        sign.append(retMsg).append("|");
        sign.append(payStatus).append("|");
        sign.append(notifyNum).append("|");
        sign.append(cardType);
        return sign.toString();
    }

    private String buildResponse(String resCode,String orderId){
        JSONObject json =  new JSONObject();
        if(StringUtils.isBlank(resCode))
            resCode = ProcCodeConstants.PROC_CODE_200F1002;

        String resMsg = dicProcCodeService.getProcCodeInfo(resCode).getMessage();
        json.accumulate("orderId", orderId);
        json.accumulate("resCode", resCode);
        json.accumulate("resMsg", resMsg);
        logger.info("cashier callback result ->resCode:"+resCode+",resMsg:"+resMsg+" for orderId:"+orderId+" at "+ DateUtils.getCurrDate());
        return json.toString();
    }

    public static void main(String[] args) {
        String test = "11111112222222222222|11.20|01|验签失败|01|1|Unknown";
        //String test1 =   "11111112222222222222|11.20|01|楠岀澶辫触|01|1|Unknown";
        String val = "IuKhUnh/Z2RBH5yLRC33fyVvys5KhqOV1W34lrNGlUUSBbGS4tc8Z0MqNVGIQ89sedhS5iRQJelM" +
                "Xo+VcdTTC36IHUT0NFAxUyivbrWzHqx0xAIir0m1jZaFCtMc2R2s6G604Ow8AMIPIDUgyN/YpaK8" +
                "fNWUF1czrHssE8nLESI=";

        try {
            String sign = RSAEncoderUtil.sign(test);
            System.out.println(sign);
            //  System.out.println( "new String :"+new String(test1.getBytes("GBK"),"UTF-8"));
            boolean flag = RSAEncoderUtil.verify(test, val);
            System.out.println(flag);
        } catch (Exception e) {
        }
    }
}
